﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.IO;
using System.Web.Script.Serialization;
using DataAccessEntLib;
using System.Text;


public partial class Classified_Cld_Edit_Ad : System.Web.UI.Page
{
    BusinessLogic busin = new BusinessLogic();
    BO.Ad bo = new BO.Ad();
    BLL.AdMagnager bll = new BLL.AdMagnager();
    DAL.AdDB _objAdDB = new DAL.AdDB(); 
    RegistrationData _objRegistrationData = new RegistrationData();
    protected int CurrentUploadImages = 0, AdID = 0;
    string ImageName = string.Empty, folderPath = string.Empty, ImagePath = string.Empty;
    public string Url = string.Empty;
    JavaScriptSerializer serializer = new JavaScriptSerializer();

    protected void Page_Load(object sender, EventArgs e)
    {
        //ImageLimit = 5; VideoLimit = 4;
        if (!object.Equals(Session["User"], null))
        {
            if (HttpContext.Current.Request.QueryString["AdID"] != null)
            {
                Page.Header.DataBind();
                if (int.TryParse(Request.QueryString["AdID"], out AdID))
                {
                    hdnAdID.Value = AdID.ToString();
                }
                if (!IsPostBack)
                {
                    BindData();
                }
                else
                {
                    if (Request.Form["__EVENTTARGET"].ToLower() == "delete")
                    {
                        if (Request.Form["__EVENTARGUMENT"] != null)
                        {
                            string args = Request.Form["__EVENTARGUMENT"].ToString().ToLower();
                            int num = 0;
                            if (Int32.TryParse(args, out num))
                            {
                                bo.AdImageVideosID = num;
                                bll.Deactivate_AdImageVideos(bo);
                            }

                        }
                    }
                }
            }
            else
            {
                Response.Redirect(Common.LogOutPage);
            }
        }
        else
        {
            Response.Redirect(Common.LogOutPage);
        }
    }

 

    void BindData()
    {
        if (int.TryParse(Request.QueryString["AdID"], out AdID))
        {
            if (!object.Equals(Session["User"], null))
            {
                _objRegistrationData = Session["User"] as RegistrationData;
                bo.UserID = _objRegistrationData.UserID;
                bo.AdID = AdID;
                if (bll.CheckAd_IsPostedByUser(bo))
                {
                    BindCategory();
                    BindSubCategory();
                    BindAdList(Convert.ToInt32(HttpContext.Current.Request.QueryString["AdID"].ToString()),_objRegistrationData.UserID);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "key", string.Format("UnAuthorized();"), true);
                }
            }
        }
    }

    protected void BindAdList(int AdID,int UserID)
    {
        if (AdID > 0)
        {
            DataSet ds = new DataSet();
            try
            {
                ds = _objAdDB.Select_AdMaster(AdID, "EditAd", UserID);
                DataRow[] dr1 = ds.Tables[0].Select("AdID=" + AdID.ToString());
                if (dr1.Length > 0)
                {
                    DataRow dr = dr1[0];
                    txtTitle.Text = Convert.ToString(dr["AdTitle"]); 
                    txtState.Text = Convert.ToString(dr["State"]);
                    txtLandMark.Text = Convert.ToString(dr["LandMark"]);
                    txtDescription.Text = Convert.ToString(dr["ProductDescription"]);
                    ddlCategory.SelectedValue = Convert.ToString(dr["AdCategoryID"]);
                    ddlSubCategory.SelectedValue = Convert.ToString(dr["SubCategoryID"]);
                }
                ds.Dispose();

                DataSet dsImageVideos = new DataSet();
                bo.AdID = AdID;
                dsImageVideos = bll.Select_AdImageVideos(bo);
                if (!object.Equals(dsImageVideos, null))
                {
                    if (dsImageVideos.Tables.Count > 0)
                    {
                        if (dsImageVideos.Tables[0].Rows.Count > 0)
                        {
                            CurrentUploadImages = dsImageVideos.Tables[0].Rows.Count;
                            StringBuilder sb = new StringBuilder();
                            foreach (DataRow dr in dsImageVideos.Tables[0].Rows)
                            {
                                if (Convert.ToString(dr["Path"]) != "images/no-image.jpg")
                                { 
                                    sb.Append("<div class='registerion_row registerion_row_none'><div class='registerion_row_left'>Upload Image</div>" +
                                    "<div class='registerion_row_right'><img src='" + Convert.ToString(dr["Path"]) + "' width='50px' height='50px' id='imgMain'/>&nbsp;&nbsp;&nbsp;&nbsp;<input style='width:50px'  type='button' value='Delete' onclick = javascript:DeleteImage(this," + Convert.ToString(dr["AdImageVideosID"]) + "," + Convert.ToString(dr["AdID"]) + ")  />" +
                                    "&nbsp;&nbsp;&nbsp;&nbsp;<a class='fbox' href='/Classified/popup/Cld-Upload-Image.aspx?AdImageVideosID=" + Convert.ToString(dr["AdImageVideosID"]) + "&ADID=" + Convert.ToString(dr["AdID"]) + "'>Upload New</a></div></div>");
                                }
                            }
                            divFiles.InnerHtml = sb.ToString();
                        }
                    }
                 
                }

            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
            }
        }
    }

  
    protected void BindCategory()
    {
        IDataReader dr;
        ddlCategory.Items.Clear();
        ListItem lst1 = new ListItem();
        lst1.Text = "Select";
        lst1.Value = "0";
        ddlCategory.Items.Add(lst1);
        dr = bll.SelectAdCategoryMaster();
        if (dr != null)
        {
            while (dr.Read())
            {
                ListItem lst = new ListItem();
                lst.Text = dr["AdCategory"].ToString();
                lst.Value = dr["AdCategoryID"].ToString();
                ddlCategory.Items.Add(lst);
            }
        }
        dr.Close();
    }

    protected void BindSubCategory()
    {
        IDataReader dr;
        ddlSubCategory.Items.Clear();
        ListItem lst1 = new ListItem();
        lst1.Text = "Select";
        lst1.Value = "0";
        ddlSubCategory.Items.Add(lst1);
        if (ddlCategory.SelectedItem.Text != "Select")
        {
            bo.AdCategoryID = Convert.ToInt32(ddlCategory.SelectedValue.ToString());
        }
        else
        {
            bo.AdCategoryID = 0;
        }
        dr = bll.ShowSubCategoryMasterDetails(bo);
        if (dr != null)
        {
            while (dr.Read())
            {
                ListItem lst = new ListItem();
                lst.Text = dr["SubCategory"].ToString();
                lst.Value = dr["SubCategoryID"].ToString();
                ddlSubCategory.Items.Add(lst);
            }
        }
        dr.Close();
    }

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        //if (Request.Form.GetValues("VideoTextBox") != null)
        //{
        //    string[] Email = Request.Form.GetValues("VideoTextBox");
        //    this.VideoLinks = serializer.Serialize(Email);
        //}
        if (Session["User"] != null)
        {
            _objRegistrationData = (RegistrationData)Session["User"];
            bo.UserID = _objRegistrationData.UserID;
        }
        if (ValidatePage())
        {
            try
            {

                //if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
                //{
                //    ImageName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                //    folderPath = "AdImages/";
                //    ImagePath = folderPath + ImageName;

                //    ImageName = busin.ValidateImageName(folderPath, ImageName);
                //    ImagePath = folderPath + ImageName;
                //    FileUpload1.PostedFile.SaveAs(Server.MapPath(ImagePath));
                //    bo.ImagePath = ImagePath;
                //}
                //else
                {
                    bo.ImagePath = GetImagePath();
                }
                bo.AdID = Convert.ToInt32(HttpContext.Current.Request.QueryString["AdID"].ToString());

                UploadDynamicImages(bo.AdID);
 
                //bo.UserID = 0;
                if (ddlCategory.SelectedItem.Text != "Select")
                    bo.AdCategoryID = Convert.ToInt32(ddlCategory.SelectedValue.ToString());
                else
                    bo.AdCategoryID = 0;

                if (ddlSubCategory.SelectedItem.Text != "Select")
                    bo.SubCategoryID = Convert.ToInt32(ddlSubCategory.SelectedValue.ToString());
                else
                    bo.SubCategoryID = 0;

                bo.AdTitle= txtTitle.Text;
                bo.ProductDescription = txtDescription.Text;
                bo.LandMark = txtLandMark.Text;
                bo.State = txtState.Text;
                bo.Country = "India";

                int strResult = 0;
                strResult = bll.UpdateAdMaster(bo);
                //  if (strResult > 0)
                {
                    lblMsg.Text = "Your ad updated successfully, to view your add <a href='/Classified/Cld-Ad-Details.aspx?AdID=" + bo.AdID.ToString() + "' style='color:#01a489'>click here.</a>";
                    divFiles.InnerHtml = string.Empty;
                    reset();
                }

            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
            }
        }
    }

    void reset()
    {
        txtTitle.Text = string.Empty; 
        txtDescription.Text = string.Empty;
        ddlCategory.SelectedIndex = 0;
        ddlSubCategory.SelectedIndex = 0; 
    }

    #region for Validation

    protected bool ValidatePage()
    {
        bool IsValidated = true;
        if (MandatoryFieldsCheck())
        {
            if (!PatternCheck())
            {
                IsValidated = false;
            }
        }
        else
        {
            IsValidated = false;
        }
        return IsValidated;
    }

    protected bool MandatoryFieldsCheck()
    {
        if (ddlCategory.SelectedItem.Text == "Select")
        {
            lblMsg.Text = "Required field - Category";
            return false;
        }

        if (ddlSubCategory.SelectedItem.Text == "Select")
        {
            lblMsg.Text = "Required field - Sub Category";
            return false;
        }
        if (txtTitle.Text == string.Empty)
        {
            lblMsg.Text = "Required field - Title";
            return false;
        }


        //if (FileUpload1.PostedFile == null && FileUpload1.FileName == string.Empty){
        //    lblMsg.Text = "Required field - Image";
        //    return false;
        //} 

        if (txtState.Text == string.Empty)
        {
            lblMsg.Text = "Required field - State";
            return false;
        }


        if (txtDescription.Text == string.Empty)
        {
            lblMsg.Text = "Required field - Description";
            return false;
        }

        return true;
    }

    protected bool PatternCheck()
    {
        bool IsPatterOK = true; 
        return IsPatterOK;
    }

    #endregion

    protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSubCategory();
    }

    void UploadDynamicImages(int AdID)
    {
        if (Request.Files != null)
        {
            HttpFileCollection hfc = Request.Files;
            string[] Uploads = Request.Form.GetValues("ImageFileUpload");
            if (hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile value = hfc[i];
                    if (value.ContentLength > 0)
                    {
                        ImageName = Path.GetFileName(value.FileName);
                        folderPath = "AdImages/";
                        ImagePath = folderPath + ImageName;

                        ImageName = busin.ValidateImageName(folderPath, ImageName);
                        ImagePath = folderPath + ImageName;
                        value.SaveAs(Server.MapPath(ImagePath));
                        bo.Path = ImagePath;
                        bo.AdID = AdID;
                        bo.IsImage = true;
                        bo.IsVideo = false;
                        bll.Insert_AdImageVideosPath(bo);
                    }
                }
            }

        }

    }

    protected string VideoLinks { get; set; }
    protected void UploadDynamicVideos(int AdID)
    {
        if (Request.Form.GetValues("VideoTextBox") != null)
        {
            string[] Email = Request.Form.GetValues("VideoTextBox");
            if (Email.Length > 0)
            {
                foreach (string value in Email)
                {
                    if (value != string.Empty)
                    {
                        bo.Path = value;
                        bo.AdID = AdID;
                        bo.IsImage = false;
                        bo.IsVideo = true;
                        bll.Insert_AdImageVideosPath(bo);
                    }
                }
            }

        }
    }

    string GetImagePath()
    {
        if (Request.Files != null)
        {
            HttpFileCollection hfc = Request.Files;
            string[] Uploads = Request.Form.GetValues("ImageFileUpload");
            if (hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile value = hfc[i];
                    if (value.ContentLength > 0)
                    {
                        ImageName = Path.GetFileName(value.FileName);
                        folderPath = "AdImages/";
                        ImagePath = folderPath + ImageName;

                        ImageName = busin.ValidateImageName(folderPath, ImageName);
                        ImagePath = folderPath + ImageName;
                        value.SaveAs(Server.MapPath(ImagePath));
                        return ImagePath;
                    }
                }
            }

        }
        return string.Empty;
    }

    string GetVideoPath()
    {
        if (Request.Form.GetValues("VideoTextBox") != null)
        {
            string[] Email = Request.Form.GetValues("VideoTextBox");
            if (Email.Length > 0)
            {
                foreach (string value in Email)
                {
                    if (value != string.Empty)
                    {
                        return value;
                    }
                }
            }

        }
        return string.Empty;
    }
}